//
//  EmotonKeyBardVC.swift
//  EmotionKeyBard
//
//  Created by 庄猛 on 17/1/12.
//  Copyright © 2017年 BeiSheng. All rights reserved.
/*
 
 lazy var keyBardVC : EmotonKeyBardVC = EmotonKeyBardVC {[weak self] (emotion) in
 self!.textView.insertEmoticon(emotion: emotion)
 }


 addChildViewController(keyBardVC)
 textView.alwaysBounceVertical = true //textView继承EmoticonTextView
 textView.keyboardDismissMode = .onDrag

 textView.inputView = keyBardVC.view//此行代码在切换键盘时调用

 
 
 print(textView.getEmoticonString())


 */

import UIKit


class EmotonKeyBardVC: UIViewController {
    lazy var collectionView: UICollectionView = {


        let temp = UICollectionView(frame: CGRect(x: 0, y: 0, width: KScreenW, height: KScreenH - 49), collectionViewLayout: EmotionKeyBardLayout())

        temp.delegate = self
        temp.dataSource = self
        temp.backgroundColor = UIColor.white

        temp.register(EmotionCollectionCell.self, forCellWithReuseIdentifier: EmotionCollectionCell.identifer())


        return temp
    }()


    lazy var bgView :UIView = {


      let temp = UIView(frame: CGRect(x: 0, y: 0, width: KScreenW, height: KScreenW/7.0 * 3 + 49))



        temp.backgroundColor = UIColor.white


        return temp


    }()




    private lazy var toolbar: UIToolbar = {
        let tb = UIToolbar()
        tb.frame = CGRect(x: 0, y: KScreenH - 44, width: KScreenW, height: 44)
        tb.backgroundColor = UIColor.orange
        tb.tintColor = UIColor.darkGray
        var items = [UIBarButtonItem]()
        for (index, title) in ["最近", "默认", "Emoji", "浪小花"].enumerated() {
            let item = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(itemClick))
            item.tag = index
            items.append(item)

            let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
            items.append(flexible)
        }
        items.removeLast()

        tb.items = items
        return tb
    }()


    var emoticonCallBack: (_ model:EmoticonFace) -> ()

    init(callBack:@escaping (_ model:EmoticonFace) -> ()){

      emoticonCallBack = callBack

    super.init(nibName: nil, bundle: nil)


    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    lazy var packages:[EmoticonPackage]? = EmoticonPackage.loadPackages()

    

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white


       setupSubViews()


        // Do any additional setup after loading the view.
    }

    private func setupSubViews(){

        view.addSubview(bgView)

        bgView.addSubview(collectionView)
        bgView.addSubview(toolbar)

        collectionView.frame =  CGRect(x: 0, y: 0, width: KScreenW, height: KScreenW/7.0 * 3)

        toolbar.frame = CGRect(x: 0, y: KScreenW/7.0 * 3 + 5, width: KScreenW, height: 44)

        // 2.布局子控件
        // 2.1禁用autoresizing
//        collectionView.translatesAutoresizingMaskIntoConstraints = false
//        toolbar.translatesAutoresizingMaskIntoConstraints = false
//
        // 2.2创建约束
//        let dict = ["collectionView": collectionView, "toolbar": toolbar] as [String : Any]
//        var cons = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
//        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[toolbar]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
//        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[collectionView]-0-[toolbar(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
//
//        // 2.3添加约束
//        bgView.addConstraints(cons)


    }



    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    // MAKR: - 内部控制方法
    @objc private func itemClick(item: UIBarButtonItem) {
        // 滚动到指定组
         collectionView.scrollToItem(at: IndexPath(item: 0, section: item.tag), at: .left, animated: false)
    }




    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

     collectionView.scrollToItem(at: IndexPath(item: 0, section: 1), at: .left, animated: false)

    }
}

extension EmotonKeyBardVC:UICollectionViewDelegate,UICollectionViewDataSource{

    func numberOfSections(in collectionView: UICollectionView) -> Int{


     return packages?.count ?? 0

    }


    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        let package = packages![section]

        return package.emoticons?.count ?? 0
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmotionCollectionCell.identifer(), for: indexPath) as! EmotionCollectionCell

       cell.model = packages?[indexPath.section].emoticons?[indexPath.item]

        return cell

    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let model =  packages?[indexPath.section].emoticons?[indexPath.item]

        emoticonCallBack(model!)

        if model!.isRemoveButton {
            return
        }

        packages?.first?.addFavoriteEmoticon(emoticon: model!)




        if indexPath.section == 0 {return}
        let indSet : IndexSet = [0]
        
        collectionView.reloadSections(indSet)


    }




}





class EmotionCollectionCell: UICollectionViewCell {

    var model : EmoticonFace?{

        didSet{

            btn.setTitle(model?.emoticonStr, for: .normal)

            btn.setImage(UIImage(), for: .normal)

            if let imageName = model?.imagePath {


                if  imageName.hasSuffix(".png") {

                    btn.setImage(UIImage(contentsOfFile: imageName), for: .normal)

                }


            }





            // 3.判断是否是删除按钮
            if model!.isRemoveButton {
                btn.setImage(UIImage(named: "compose_emotion_delete"), for: .normal)
            }




        }

    }



    lazy var btn : UIButton = {
     let temp = UIButton()
    temp.backgroundColor = UIColor.clear

        temp.titleLabel?.font = UIFont.systemFont(ofSize: 32)
        temp.isUserInteractionEnabled = false

     return temp
    }()


     override init(frame: CGRect) {
        super.init(frame: frame)
    contentView.backgroundColor = UIColor.white
     contentView.addSubview(btn)

    }


    override func layoutSubviews() {

        super.layoutSubviews()

        btn.frame = bounds.insetBy(dx: 2, dy: 2)

        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    class func identifer() -> String{

        return NSStringFromClass(self)
        
    }


}



class EmotionKeyBardLayout: UICollectionViewFlowLayout {



    override func prepare() {
     super.prepare()


    let screenW = UIScreen.main.bounds.size.width
        let itemW = screenW / 7.0
    itemSize =  CGSize(width: itemW, height: itemW)

        scrollDirection = .horizontal
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0


       collectionView?.showsVerticalScrollIndicator = false
       collectionView?.showsHorizontalScrollIndicator = false
       collectionView?.isPagingEnabled = true
        collectionView?.bounces = false



        // 3.让cell居中显示
        let offsetY = collectionView!.bounds.height - 3 * itemW - 0.1
        collectionView?.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: offsetY, right: 0)


    }
    
    

}

